package com.p7.notepad.activity;

import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.p7.notepad.R;
import com.p7.notepad.app.BaseActivity;
import com.p7.notepad.bean.Success;
import com.p7.notepad.network.APIManager;
import com.p7.notepad.network.exception.ExceptionHandle;
import com.p7.notepad.network.listener.RequestListener;
import com.p7.notepad.tools.Storage;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class AddFileActivity extends BaseActivity {

    @BindView(R.id.add_file_name)
    EditText mName;

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_file;
    }

    @OnClick({R.id.add_file_quit, R.id.add_file_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_file_quit:
                finish();
                break;
            case R.id.add_file_btn:
                submit();
                break;
        }
    }

    private void submit() {
        String name = mName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "文件夹名称不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, String> parameters = new HashMap<>();
        parameters.put("userId", String.valueOf(Storage.getId()));
        parameters.put("name", name);
        APIManager.onPost("folder/newFolder", parameters, new RequestListener() {
            @Override
            public void onSuccess(String s) {
                Gson gson = new Gson();
                Success success = gson.fromJson(s, Success.class);
                if (success.getCode() == 1000) {
                    finish();
                } else if(success.getCode() == 2001) {
                    startActivity(LoginActivity.class);
                    finish();
                } else {
                    setToast(success.getMessage() + "请稍后重试");
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponeThrowable error) {
                setToast(error.message);
            }
        });

    }

    private void setToast(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }
}
